<?php
namespace Swiftx\Bundle\WeChat\Controller\Company;
use Swiftx\Bundle\WeChat\Interfaces\Common\AjaxController;
use Swiftx\Bundle\WeChat\Interfaces\Controller\Company\Album as AlbumInterface;
use Swiftx\Bundle\WeChat\Factory\Company as CompanyFactory;
use Swiftx\Bundle\WeChat\Factory\Album as AlbumFactory;
use Swiftx\Bundle\WeChat\Model\Seller\Album as AlbumModel;
use Swiftx\Bundle\WeChat\Model\Seller\Image;
use Swiftx\Bundle\WeChat\System\Config;
use Swiftx\Interfaces\Httpd\Request;
use Swiftx\Interfaces\Httpd\Response;

/**
 * 用户登录页面实现
 */
class Album extends AjaxController implements AlbumInterface {

    /**
     * 企业工厂实例
     * @var CompanyFactory
     * @auto-injection
     */
    protected $companyFactory;

    /**
     * 相册工厂实例
     * @var AlbumFactory
     * @auto-injection
     */
    protected $albumFactory;

    /**
     * 模块配置实例
     * @var Config
     * @auto-injection
     */
    protected $config;

    /**
     * 显示所有相册
     * @param Request $request
     * @param Response $response
     * @router method   get
     * @return bool
     */
    public function showList(Request $request, Response $response):bool{
        // 获取当前用户
        $company = $this->companyFactory->currentLogin($request);
        if(empty($company))
            return $this->errorDisplay($response, '用户未登录');
        $album_list = $company->getAlbums();
        // 拼装数据集合
        $result = [];
        foreach($album_list as $album){
            $temp['id'] = $album->getID();
            $temp['title'] = $album->getTitle();
            $temp['count'] = $album->countImages();
            $result[] = $temp;
        }
        // 渲染输出结果
        return $this->successDisplay($response, $result);
    }

    /**
     * 创建新相册
     * @param Request $request
     * @param Response $response
     * @return bool
     */
    public function create(Request $request, Response $response):bool {
        // 获取当前用户
        $company = $this->companyFactory->currentLogin($request);
        /** @var AlbumModel $new_album */
        $new_album = $this->container->create(AlbumModel::class);
        $new_album->setCompany($company->getID());
        $new_album->setTitle($request->getPost()->get('title'));
        // 执行数据写入
        $this->entityManager->save($new_album);
        $this->entityManager->flush();
        // 返回执行结果
        $result['id'] = $new_album->getID();
        $result['title'] = $new_album->getTitle();
        return $this->successDisplay($response, $result);
    }

    /**
     * 显示相册图片
     * @param Request $request
     * @param Response $response
     * @return bool
     */
    public function showDetail(Request $request, Response $response):bool{
        // 获取当前用户
        $company = $this->companyFactory->currentLogin($request);
        $album = $this->albumFactory->fetchByID($request->getParam('id'));
        // 访问权限检测
        if($company->getID() != $album->getCompanyID())
            return $this->errorDisplay($response, '无该相册访问权限！');
        // 响应相册数据
        $data['id'] = $album->getID();
        $data['title'] = $album->getTitle();
        $page = $album->getImagePage((int)$request->getParam('page'),24);
        $data['total'] = $page->getTotal();
        // 响应分页信息
        $data['page'] = [
            'number' => $page->getNumber(),
            'total' => $page->getCount()
        ];
        // 响应图片列表
        $data['list'] = [];
        /** @var Image $image */
        foreach($page->getData() as $image){
            $data['list'][] = [
                'id' => $image->getID(),
                'url' => $image->getUrl()
            ];
        }
        // 显示页面结果
        return $this->successDisplay($response, $data);
    }

    /**
     * 图片上传
     * @param Request $request
     * @param Response $response
     * @return bool
     */
    public function upload(Request $request, Response $response):bool {

        // 获取当前用户
        $company = $this->companyFactory->currentLogin($request);
        $album = $this->albumFactory->fetchByID($request->getPost()->get('album'));

        // 用户用户默认相册不存
        if($album == null) return $this->errorDisplay($response,'相册不存在');

        // 访问权限检测
        if($company->getID() != $album->getCompanyID())
            return $this->errorDisplay($response, '无该相册访问权限！');

        /** @var Image $new_image */
        $new_image = $this->container->create(Image::class);
        $upload = $request->getUpload('file');

        // 构造相册数据
        $new_image->setAlbum($album->getID());
        $file_name = $new_image->getID().'.'.$upload->getExtName();
        $new_image->setPath($this->config->get('album.public').'/'.$file_name);
        $new_image->setUrl($this->config->get('album.url').'/'.$file_name);

        // 存储数据和文件
        $dir = $this->config->get('album.public');
        if(!file_exists($dir))
            mkdir($dir, 0777, true);
        $upload->save($new_image->getPath());
        $this->entityManager->save($new_image);
        $this->entityManager->flush();

        // 相应数据结果
        $result['id'] = $new_image->getID();
        $result['url'] = $new_image->getUrl();
        return $this->successDisplay($response, $result);

    }

}